<?php


namespace app\api\controller\v1;


use app\api\controller\v1\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use Predis\Command\Redis\DUMP;
use think\Db;

/**
 * 天津中融
 * 账户：15900302222
 */
class TianJingZhongRong
{
    private $acKey;
    private $publicKey;

    public function __construct() {

            $this->acKey = '8a54beccd3c906064078453f72b79dd3';
            $this->publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXXaohJEjpjVL6xfqQ2ghsJfSOsojRXEOsaW+71chLGN09VIH+jWbBKVzT5b9oxHiaoAtNbHwseysoS389T6BLDWIY3wPVKddzSeUyqeG7hH5jh9xQYGB7zXCmXSdbiXzlXi/cem/POlbUk/vJiPhH/CW6OSeoRnvvqdyrvsZMQIDAQAB';

    }

    public function pushClue($mapping,$clue_info,$listPush)
    {

        $apiName='【'.$mapping['api_name'].'】';

//        $clue_info['clue_name']='测试张';
//        $clue_info['phone']='13000000001';

        $this->getValidate($apiName,$clue_info); // 手机号码的撞库
        $clue_rule = json_decode($mapping['rule_json'], true);
        $params = [];
        if(!$clue_rule){
            $errMsg=$apiName.'读取商户接收规则失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }else{

            foreach ($clue_rule as $v){
                $params[$v['curr']] = $clue_info[$v['orig']];
                if($v['orig'] == 'city'){
                    $citys = explode('-',$clue_info[$v['orig']]);
                    $city_info = Db::name('city')->where(['type'=>2,'id'=>$citys[1]])->find();
                    $params[$v['curr']] = $city_info['name'];
                }
            }

            $params['t3']=1;
//            if(strpos($clue_info['apply_limit'], '万') !== false){
//                $params['t4']=intval($clue_info['apply_limit'])*10000;
//            }else{
//                $params['t4']=intval($clue_info['apply_limit']);
//            }

            if(strpos($clue_info['apply_limit'], '-') !== false){
                $moneyArr=explode('-',$clue_info['apply_limit']);
                $moneyNum=count($moneyArr);
                if($moneyNum==1){
                    $MoneyStr=$moneyArr[0];
                }else{
                    $MoneyStr=$moneyArr[1];
                }
            }else{
                $MoneyStr=$clue_info['apply_limit'];
            }
            if(strpos($MoneyStr, '万') !== false){
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $params['t4']=intval($MoneyStr)*10000;
            }else{
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $params['t4']=intval($MoneyStr);
            }
            if(empty($params['t4'])){
                $params['t4']=10000;
            }

            $params['t5']=1;
            $params['t7']='抖音36';


            if (!empty($clue_info['show_city'])) {
                if (strpos($clue_info['show_city'], '-') !== false) {
                    $city_t = explode('-', $clue_info['show_city']);
                    $city_info = clue_city_transform($city_t);
                }else{
                    $params['city']=$clue_info['show_city'];
                    $city_info=Db::name('city')->where(['type' => 2, 'name' => $clue_info['show_city']])->find();
                }
                if(empty($city_info)){
                    $errMsg=$apiName.'显示城市匹配失败';
                    ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
                    model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                    throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
                }else{
                    $params['t9']=$city_info['code'];
                    $params['t8']=Db::name('city')->where(['id'=>$city_info['pid']])->value('code');
                }
            }else{
                if(!empty($clue_info['city'])){
                    $citys = explode('-',$clue_info['city']);
                    $city_info1 = Db::name('city')->where(['id'=>$citys[0]])->find();
                    $city_info2 = Db::name('city')->where(['id'=>$citys[1]])->find();

                    $params['t8']=$city_info1['code'];//省code
                    $params['t9']=$city_info2['code'];//市code
                }
            }


            //渠道

            if(!empty($clue_info['push_channel'])){
                $source=$clue_info['push_channel'];
            }else{
                $advInfo=Db::name('account')->where('adv_id',$clue_info['adv_id'])->find();
                $source=$advInfo['show_channel'];
                if(empty($source)){
                    $source=get_channel_desc($clue_info['type']);

                }
            }
            $remarkStr=$source.'-';


            if(empty($clue_info['remark'])){
            }else{
                $remark=json_decode($clue_info['remark'],true);
                if (is_array($remark)){
                    $remarkArr=[];
                    $keys=array_keys($remark);
                    $b=false;//默认索引
                    //判断关联数组还是索引数组
                    foreach($keys as $value){
                        if(!is_int($value)){
                            $b=true;
                            break;
                        }
                    }
                    //是关联数组
                    if($b){
                        foreach ($remark as $kk=>$vv){
                            if(strpos($kk, '城市') !== false){
                            }else{
                                $remarkArr[]=$vv;
                            }
                        }
                    }else{
                        foreach ($remark as $vv){
                            if($clue_info['type']==1){
                                if(strpos($vv['name'], '城市') !== false){
                                }else{
                                    $remarkArr[]=$vv['value'];
                                }
                            }else{
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    if(strpos($vv['name'], '城市') !== false){
                                    }else{
                                        $remarkArr[]=$vv['value'];
                                    }
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                }else{
                    $remarkArr[]=$remark;
                }
                $remarkStr=$remarkStr.implode('|',$remarkArr);
            }

            $params['t10']=$remarkStr;

//
//            dump('参数');
//            dump($params);
//            die;

            //生成签名
            ksort($params);
            $str='';
            foreach ($params as $key => $value) {
                if($value!=null){
                    $str .= $key . $value;
                }
            }
//            \dump('签名串');
//            \dump($str);
            $sign=md5($str);
            $params['sign']=strtoupper($sign);

//            \dump('签名后');
//            \dump($params);

            $codeParam=[];
            foreach ($params as $k=>$v){
                $codeParam[$k]=$this->rsa($v);
            }

//            \dump('加密后');
//            \dump($codeParam);

            $api_url = $mapping['api_url'];

            $postApi=[
                'accessKey'=>$this->acKey,
                'requestId'=>uuid(),
                'data'=>[$codeParam]
            ];
            $postData['data']=$postApi;
            $postData['param']=$params;

//            \dump('提交');
//            \dump($api_url);
//            \dump($postApi);
            // 2. 推送线索
            $res_json = $this->postJson($api_url, $postApi);
            $res  = json_decode($res_json, true);
//            dump($res);
//            die;
            if(!empty($res)){
                $res['params'] = $postData;
                if($res['code']!=200){
                    $errMsg=$apiName.'线索推送商户处理失败';
                    ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                    model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg.$res['msg']]);
                    throw new ParamException(['msg'=>$errMsg.$res['msg'],'errorCode'=>10001]);
                }else{
                    //看DATA0 是否有数据成功
                    if(!empty($res['data'][0])){
                        if(strpos($res['data'][0], '数据成功') === false) {
                            $errMsg=$apiName.'线索推送商户处理失败';
                            ClueErrorLog::record($clue_info['clue_id'],'线索推送商户处理失败',$res);
                            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg.$res['data'][0]]);
                            throw new ParamException(['msg'=>$errMsg.$res['data'][0],'errorCode'=>10001]);
                        }
                    }else{
                        $errMsg=$apiName.'线索推送商户处理失败';
                        ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                        model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg.$res['msg']]);
                        throw new ParamException(['msg'=>$errMsg.$res['msg'],'errorCode'=>10001]);
                    }
                }
            }else{
                $errMsg=$apiName.'线索推送商户请求失败';
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$postData);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }

            return $res;
        }
    }

    //$data 待加密数据;
    private function rsa($data){
        $publcKeyStr = $this->publicKey;
        $crypted = 'yagamizn';
        $public_key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($publcKeyStr, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
        $isvalid = openssl_public_encrypt($data, $crypted , $public_key ,OPENSSL_PKCS1_PADDING);

        //echo "加密后 : ".base64_encode($crypted);
        return base64_encode($crypted);
    }

    //可以直接用
    public function getValidate($apiName,$clue_info)
    {
        $phone=$clue_info['phone'];
        $api_url = 'https://www.xz9898.com:8543/qingyu3/access/phoneMd5Check';

        $api_params = [
            'accessKey'=>$this->acKey,
            'requestId'=>uuid(),
            'data'=>[
                ['phone'=> md5($phone)]
            ]
        ];
        $res_json = $this->postJson($api_url, $api_params);
        $res  = json_decode($res_json, true);

//        \dump($res);die;

        if(!empty($res)){
            if($res['code']!=200){
                $errMsg=$apiName.'CRM手机号码的撞库失败';
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg.$res['msg']]);
                throw new ParamException(['msg'=>$res['msg'],'errorCode'=>10001]);
            }else{
                if(!empty($res['data'])){

                    $errMsg=$apiName.'CRM手机号码的撞库重复';
                    ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                    model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                    throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);

//                    if(empty($clue_info['is_find'])&&!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city']){
//                        $clue_info['city'] = $clue_info['clue_city'];
//                        $clue_info['next_city'] = $clue_info['clue_city'];
//                        $listPush[]=$clue_info['push_id'];
//                        $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                        if($clueRes['code']!=200){
//                            $errMsg=$clueRes['msg'];
//                            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }else{
//                        $errMsg=$apiName.'CRM手机号码的撞库重复';
//                        ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                        model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                        $isRe=Db::name('clue_err_log')->where(['type'=>2,'adv_id'=>$clue_info['adv_id'],'pro_id'=>$clue_info['pro_id'],'clue_id'=>$clue_info['id']])->find();
//                        if(empty($isRe)){
//                            Db::name('clue_err_log')->insert([
//                                'type'=>2,
//                                'clue_id'=>$clue_info['id'],
//                                'adv_id'=>$clue_info['adv_id'],
//                                'pro_id'=>$clue_info['pro_id'],
//                                'city'=>$clue_info['city'],
//                                'create_time'=>time()]);
//                        }
//                        if(empty($clue_info['is_find'])){
//                            $listPush[]=$clue_info['push_id'];
//                            $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                            if($clueRes['code']!=200){
//                                $errMsg=$clueRes['msg'];
//                                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                            }
//                        }else{
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }
                }
            }
        }else{
            $errMsg=$apiName.'CRM手机号码的撞库请求失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }
        return $res;
    }

    public function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }

    /**
     * post发送json格式的数据
     */
    public function postJson($url, $data)
    {

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            throw new ParamException(['msg'=>'请求数据不能为空','errorCode'=>10000]);
        }
        $data=json_encode($data,JSON_UNESCAPED_UNICODE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
//            'token:3dcb0d2dba347b40476bc3294c60fdfe' ,

        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

}